import request from '@/utils/request'
import { getLocalChannels, hasToken, localChannels } from '@/utils/storage'
import {
  SAVE_ALLCHANNELS,
  SAVE_ARTICLES,
  SAVE_CHANNELS,
} from '../actionType/home'

export const getChannels = () => {
  return async (dispatch) => {
    if (hasToken()) {
      const res = await request({
        method: 'get',
        url: 'user/channels',
      })
      dispatch(channelsReducers(res.data.channels))
    } else {
      if (getLocalChannels()) {
        dispatch(channelsReducers(getLocalChannels()))
      } else {
        const res = await request({
          method: 'get',
          url: 'user/channels',
        })
        dispatch(channelsReducers(res.data.channels))
        localChannels(res.data.channels)
      }
    }
  }
}

// 频道列表存到reducers
export const channelsReducers = (payload) => {
  return {
    type: SAVE_CHANNELS,
    payload,
  }
}

// 获取全部频道
export const getAllChannels = () => {
  return async (dispatch) => {
    const res = await request({
      method: 'get',
      url: '/channels',
    })
    // console.log(res)
    dispatch({
      type: SAVE_ALLCHANNELS,
      payload: res.data.channels,
    })
  }
}
// 删除单个频道
export const delChannelsVal = (channels1) => {
  return async (dispatch, getState) => {
    console.log(getState())
    const { channels } = getState().home
    console.log(channels)
    if (hasToken()) {
      await request.delete('user/channels/' + channels1.id)
      dispatch(
        channelsReducers(channels.filter((item) => item.id !== channels1.id))
      )
    } else {
      const itemVal = channels.filter((item) => item.id !== channels1.id)
      localChannels(itemVal)
      dispatch(channelsReducers(itemVal))
    }
  }
}

// 添加频道
export const addChannelsVal = (channels1) => {
  return async (dispatch, getState) => {
    const itemVal = [...getState().home.channels, channels1]
    if (hasToken()) {
      await request.patch('user/channels', {
        channels: [channels1],
      })
      dispatch(channelsReducers(itemVal))
    } else {
      dispatch(channelsReducers(itemVal))
      localChannels(itemVal)
    }
  }
}

// 获取列表文章
export const getArticlesLsit = (channelId, timestamp, isLoadMore = false) => {
  return async (dispatch) => {
    const res = await request({
      method: 'get',
      url: '/articles',
      params: {
        timestamp: timestamp,
        channel_id: channelId,
      },
    })
    // console.log(res)
    // console.log(isLoadMore)
    dispatch(
      setArticleList({
        channelId,
        timestamp: res.data.pre_timestamp,
        list: res.data.results,
        isLoadMore,
      })
    )
  }
}
export const setArticleList = (payload) => {
  return {
    type: SAVE_ARTICLES,
    payload,
  }
}

/**
 * 设置举报反馈菜单信息
 */
export const setFeedbackAction = ({ visible, articleId }) => ({
  type: 'home/feedback_action',
  payload: {
    visible,
    articleId,
  },
})
